<?php
/**
 * Creater: 李青林
 * Date Time : 2018/8/15 13:43
 */

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Cache;
use App\Http\Models\Region;
use Validator;
use Illuminate\Http\Request;

class RegionController extends Controller
{
    /**
     * 获取所有的省份
     * @return string
     */
    public function getProvinceInfo()
    {
        $province = Cache::remember('ProvinceInfo', 60, function () {
            return Region::select('name', 'id')->where('parent_id', 0)->get();
        });
        return json_encode(['code' => 0, 'msg' => 'ok', 'data' => $province]);
    }

    /**
     * 获取1个省份下的所有市区以及市区下的
     * @return string
     */
    public function getCity(Request $request)
    {
        $province_id = $request->input('province_id') ? $request->input('province_id') : 1;
        $city = Cache::remember('City:' . $province_id, 60, function () use ($province_id) {
            $city = Region::select('name', 'id')->where('parent_id', $province_id)->get();
            if ($city) {
                $city = $city->toArray();
                foreach ($city as $key => $value) {
                    $city[$key]['area'] = Region::select('name', 'id')->where('parent_id', $value['id'])->get();
                }
            }
            return $city;
        });
        return json_encode(['code' => 0, 'msg' => 'ok', 'data' => $city]);
    }
}